package cn.itcast.order.task;

import cn.itcast.feign.client.ItemClient;
import cn.itcast.hmall.pojo.item.Item;
import cn.itcast.hmall.pojo.order.Order;
import cn.itcast.hmall.pojo.order.OrderDetail;
import cn.itcast.order.mapper.OrderDetailMapper;
import cn.itcast.order.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class StockJob {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ItemClient itemClient;
    @XxlJob("hema_job_test")
    public void jobTest(){
        LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Order::getStatus,1);
        List<Order> list = orderService.list(wrapper);
        for (Order order : list) {
            Date createTime = order.getCreateTime();
            Date date = new Date();
            long minutes = ChronoUnit.MINUTES.between(Instant.ofEpochMilli(createTime.getTime()), Instant.ofEpochMilli(date.getTime()));
            if(minutes>=30L){
                order.setStatus(5);
                orderService.updateById(order);
                LambdaQueryWrapper<OrderDetail> wrapper2 = Wrappers.lambdaQuery();
                wrapper2.eq(OrderDetail::getOrderId,order.getId());
                OrderDetail orderDetail = orderDetailMapper.selectOne(wrapper2);
                Item item = new Item();
                item.setId(orderDetail.getItemId());
                item.setStock(orderDetail.getNum());
                itemClient.addUpdate(item);
            }
        }
    }
}
